//
//  LanOuMusic.m
//  SongsPlay
//
//  Created by 漫步人生路 on 15/6/28.
//  Copyright (c) 2015年 漫步人生路. All rights reserved.
//

#import "LanOuMusic.h"
#import "LORequestManger.h"
#define kSongUrl @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=webapp_music&method=baidu.ting.song.play&format=json&callback=&songid="
#define kSongUrlWithSongid @"&_=1413017198449"
@implementation LanOuMusic
static LanOuMusic *lanOuMusic;
//创建单例
+ (LanOuMusic *)shareMusic
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lanOuMusic = [[LanOuMusic alloc]init];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didFinsh) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
    });
    return lanOuMusic;
}
- (void)didFinsh
{
    NSLog(@"播放完了");
    self.isPlaying = NO;
}
- (BOOL)isPlayingCurrentAudioWithUrl:(NSString *)url
{
    NSString *currentUrl = [(AVURLAsset *)self.wxPlayer.currentItem.asset URL].absoluteString;
    return [currentUrl isEqualToString:url];
}
- (NSMutableArray *)songIDArray
{
    if (!_songIDArray) {
        _songIDArray = [[NSMutableArray alloc]init];
    }
    return _songIDArray;
}
//使用懒加载创建我们的wxPlayer（什么时候用什么时候创建）
- (AVPlayer *)wxPlayer
{
    if (!_wxPlayer) {
        _wxPlayer = [[AVPlayer alloc]init];
    }
    return _wxPlayer;
}
//根据我们当前歌曲的链接来获取我们歌曲的所有信息
- (void)playMusicWithUrl:(NSString *)url
{
    //切记移除观察者
    if (self.wxPlayItem) {
        [self.wxPlayItem removeObserver:self forKeyPath:@"status"];
    }
    //首先我们创建一个item，通过url来获取歌曲的所有信息
    self.wxPlayItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    //添加一个观察者来观察我们当前歌曲的缓冲状态
    [self.wxPlayItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    //使用AVPlayer对象来替换item（白话含义就是替换一首歌的信息）
    [self.wxPlayer replaceCurrentItemWithPlayerItem:self.wxPlayItem];
    
}
//开始播放
- (void)starPlayMusic
{

    self.isPlaying = YES;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //通过观察者获取我们self.youCanPlay的值来判断是否可以播放
    if (self.youCanPlay == YES) {
        //开始播放
        [self.wxPlayer play];
    }
    //判断我们的timer是否存在
    if (self.timer) {
        return;
    }
    //创建一个计时器，并且添加一个事件，当我们开始播放的时候就启动并执行
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timerMonitoring:) userInfo:nil repeats:YES];
}
//计时器执行方法
- (void)timerMonitoring:(NSTimer *)sender
{
    if (self.youCanPlay == YES) {
        _progress = self.wxPlayer.currentTime.value / self.wxPlayer.currentTime.timescale;
        [self.delegate audioStreamer:self didPlayingWithProgress:_progress];
    }
}
//停止播放
- (void)stopMusic
{
    self.isPlaying = NO;
    //暂停
    [self.wxPlayer pause];
    [self.timer invalidate];
    self.timer = nil;
}
//跳转到指定的时间点
- (void)seekToTime:(float)time
{
    //拖动时暂停
    [self stopMusic];
    [self.wxPlayer seekToTime:CMTimeMakeWithSeconds(time, self.wxPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            //拖动完毕开始播放
            [self starPlayMusic];
        }
    }];
}
//实现观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //如果不理解这个change的话可以打印一下他的keys
    NSLog(@"%@",change.allKeys);
    //change是一个字典，内部包含着kind，old，new的key
    //我们每次观察都是观察最新一首歌的状态，所以这里给一个new
    switch ([change[@"new"] intValue]) {
        //判断AVPlayerItem的缓冲状态
        //此处容易粗心大意写成AVPlayerStatus
        //切记是AVPlayerItemStatus
        
        //给定一个BOOL类型的属性，当我们的歌曲缓冲完成的时候让他等于yes，外部调用可以根据它来判断是否可以播放
        case AVPlayerItemStatusFailed:
            self.youCanPlay = NO;
            NSLog(@"缓冲失败");
            break;
        case AVPlayerItemStatusReadyToPlay:
            self.youCanPlay = YES;
            NSLog(@"缓冲成功");
            break;
        case AVPlayerStatusUnknown:
            self.youCanPlay = NO;
            NSLog(@"状态未知");
            break;
        default:
            break;
    }
}
//解析网络数据
- (void)loadDataWithSongsWithSongID:(NSString *)songID
{
    NSString *url = [[kSongUrl stringByAppendingString:songID] stringByAppendingString:kSongUrlWithSongid];
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *bitrate = dic[@"bitrate"];
        self.songUrl = bitrate[@"file_link"];
        [self playMusicWithUrl:self.songUrl];
        self.maxValue = bitrate[@"file_duration"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}








@end
